package com.jy.horny.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.Animatable
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.ImageView
import com.jy.horny.R

class LoadingDialog private constructor(context: Context, theme: Int) : Dialog(context, theme) {
    private var params: Params? = null
    private class Params {
        lateinit var mContext: Context
        var hasShadow = false
        var canCancel = true
        lateinit var loadingView: ImageView
    }

    class Builder(context: Context) {
        private val p = Params()

        init {
            p.mContext = context
        }

        fun show() {
            create().show()
        }

        fun setCancelable(cc: Boolean): Builder {
            p.canCancel = cc
            return this
        }

        fun create(): LoadingDialog {
            val dialog = LoadingDialog(
                    p.mContext,
                    if (p.hasShadow) com.lib.module_res.R.style.Theme_Light_NoTitle_Dialog else com.lib.module_res.R.style.Theme_Light_NoTitle_NoShadow_Dialog
            )

            val window = dialog.window
            if (window != null) {
                val lp = window.attributes
                lp.width = WindowManager.LayoutParams.WRAP_CONTENT
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT
                window.attributes = lp
            }

            @SuppressLint("InflateParams") val view = LayoutInflater.from(p.mContext)
                    .inflate(R.layout.dialog_simple_loading, null)
            p.loadingView = view.findViewById(R.id.loading)

            dialog.params = p
            dialog.setContentView(view)
            dialog.setCanceledOnTouchOutside(p.canCancel)
            dialog.setCancelable(p.canCancel)
            return dialog
        }
    }

    override fun dismiss() {
        super.dismiss()
        (params?.loadingView?.drawable as? Animatable)?.stop()
    }

    override fun show() {
        super.show()
        (params?.loadingView?.drawable as? Animatable)?.start()
    }


}